// import React from 'react'
import { Spin, Alert, Pagination } from 'antd';
import fetchJsonp from 'fetch-jsonp'
import Movieitem from './movieItem.jsx'

export default class movielist extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      movies: [], //电影列表
      nowPage: parseInt(this.props.match.params.page) || 1, //请求第几页的数据
      pageSize: 12, //请求多少条数据
      total: 0, //返回的总数据
      isloading: true,
      movieType: this.props.match.params.type
    }
  }

  // 组件要接收新的数据时就会触发该函数
  componentWillReceiveProps(nextProps) {
    this.setState({
      nowPage: parseInt(nextProps.match.params.page) || 1,
      isloading: true,
      movieType: nextProps.match.params.type
    }, () => {
      this.fetchgetList()
    })
  }

  renderList = () => {
    if (this.state.isloading) {
      return <Spin tip="Loading...">
        <Alert
          message="Alert message title"
          description="Further details about the context of this alert."
          type="info"
        />
      </Spin>
    } else {

      return <div>
        <div style={{ display: 'flex', flexWrap: 'wrap' }}>
          {
            this.state.movies.map((item, index) => {
              return <Movieitem {...item} key={index} />
            })
          }
        </div>
        <Pagination defaultCurrent={this.state.nowPage} pageSize={this.state.pageSize} total={this.state.total} onChange={this.pageChanged} />
      </div>
    }
  }


  componentWillMount() {
    this.fetchgetList()
  }

  pageChanged = (page) => {
    this.props.history.push('/movie/' + this.state.movieType + '/' + page)
  }

  fetchgetList = () => {
    const start = this.state.pageSize * (this.state.nowPage - 1)
    const url = `https://douban.uieee.com/v2/movie/${this.state.movieType}?start=${start}&count=${this.state.pageSize}?city=邯郸`

    fetchJsonp(url).then(res => res.json()).then(res => {
      this.setState({
        isloading: false,
        total: res.total,
        movies: res.subjects.length > 12 ? res.subjects.slice(0, 12) : res.subjects
      })
    })
  

  }

  render() {
    return (
      <div style={{ backgroundColor: "#fff" }}>
        {
          this.renderList()
        }
      </div>
    )
  }

}
